<?php
declare(strict_types=1);

namespace app\model;

use think\Model;
use think\facade\Cache;

class MerchantPaymentConfig extends Model
{
    protected $name = 'merchant_payment_config';
    
    protected $autoWriteTimestamp = true;
    
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';

    // 支付方式
    const PAYMENT_WECHAT = 1;  // 微信支付
    const PAYMENT_ALIPAY = 2;  // 支付宝支付
    const PAYMENT_BALANCE = 3; // 余额支付

    // 状态
    const STATUS_ENABLED = 1;  // 启用
    const STATUS_DISABLED = 2; // 禁用

    /**
     * 获取配置详情
     */
    public static function getConfigDetail(int $merchantId, int $paymentMethod): ?array
    {
        // 尝试从缓存获取
        $cacheKey = "payment_config:{$merchantId}:{$paymentMethod}";
        $config = Cache::get($cacheKey);

        if (!$config) {
            // 从数据库获取
            $model = self::where([
                'merchant_id' => $merchantId,
                'payment_method' => $paymentMethod,
                'status' => self::STATUS_ENABLED
            ])->find();

            if (!$model) {
                return null;
            }

            $config = $model->toArray();
            
            // 解析配置信息
            $config = array_merge($config, json_decode($config['payment_config'], true) ?: []);

            // 缓存配置
            Cache::set($cacheKey, $config, 3600);
        }

        return $config;
    }

    /**
     * 更新配置
     */
    public static function updateConfig(int $merchantId, int $paymentMethod, array $config): bool
    {
        // 验证支付方式
        if (!in_array($paymentMethod, [self::PAYMENT_WECHAT, self::PAYMENT_ALIPAY])) {
            throw new \Exception('不支持的支付方式');
        }

        // 验证配置
        self::validateConfig($paymentMethod, $config);

        // 查找已有配置
        $model = self::where([
            'merchant_id' => $merchantId,
            'payment_method' => $paymentMethod
        ])->find();

        if ($model) {
            // 更新配置
            $result = $model->save([
                'payment_config' => json_encode($config, JSON_UNESCAPED_UNICODE),
                'status' => self::STATUS_ENABLED
            ]);
        } else {
            // 创建配置
            $result = self::create([
                'merchant_id' => $merchantId,
                'payment_method' => $paymentMethod,
                'payment_config' => json_encode($config, JSON_UNESCAPED_UNICODE),
                'status' => self::STATUS_ENABLED
            ]);
        }

        if ($result) {
            // 清除缓存
            Cache::delete("payment_config:{$merchantId}:{$paymentMethod}");
        }

        return (bool)$result;
    }

    /**
     * 验证配置
     */
    protected static function validateConfig(int $paymentMethod, array $config): bool
    {
        switch ($paymentMethod) {
            case self::PAYMENT_WECHAT:
                if (empty($config['app_id'])) {
                    throw new \Exception('微信AppID不能为空');
                }
                if (empty($config['mch_id'])) {
                    throw new \Exception('微信商户号不能为空');
                }
                if (empty($config['key'])) {
                    throw new \Exception('微信API密钥不能为空');
                }
                if (empty($config['cert_path'])) {
                    throw new \Exception('微信证书路径不能为空');
                }
                if (empty($config['key_path'])) {
                    throw new \Exception('微信证书密钥路径不能为空');
                }
                if (empty($config['v3_key'])) {
                    throw new \Exception('微信APIv3密钥不能为空');
                }
                break;

            case self::PAYMENT_ALIPAY:
                if (empty($config['app_id'])) {
                    throw new \Exception('支付宝AppID不能为空');
                }
                if (empty($config['merchant_private_key'])) {
                    throw new \Exception('支付宝商户私钥不能为空');
                }
                if (empty($config['alipay_public_key'])) {
                    throw new \Exception('支付宝公钥不能为空');
                }
                break;
        }

        return true;
    }

    /**
     * 禁用配置
     */
    public static function disableConfig(int $merchantId, int $paymentMethod): bool
    {
        $result = self::where([
            'merchant_id' => $merchantId,
            'payment_method' => $paymentMethod
        ])->update(['status' => self::STATUS_DISABLED]);

        if ($result) {
            // 清除缓存
            Cache::delete("payment_config:{$merchantId}:{$paymentMethod}");
        }

        return (bool)$result;
    }
} 